<template>
  <div>
    <el-carousel :interval="4000" type="card" style="margin-top: 20px" height="300px">
    <el-carousel-item v-for="(image, index) in activityImage" :key="index">
      <img :src="image" alt="Activity Image" style="width: 100%; height: 100%;" />
    </el-carousel-item>
  </el-carousel>
    <div class="activity-list">
    <!-- 活动列表 -->
    <div class="activity_table" style="margin-top:15px;margin-left: -10px">
      <el-table :data="activities" style="width: 100%" border>
        <el-table-column label="活动名称">
          <template slot-scope="scope">
            <el-button type="text" @click="turnActivity(scope.row.id)" style="cursor: pointer">{{ scope.row.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="活动类型" prop="type">
          <template slot-scope="{ row }">
            <span v-if="row.type === 1">线上</span>
            <span v-else-if="row.type === 2">校内</span>
            <span v-else-if="row.type === 3">校外</span>
          </template>
        </el-table-column>
        <el-table-column label="人数信息">
          <template slot-scope="scope">
            <span>{{ scope.row.activityNum }} / {{ scope.row.activityMaxNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报名时间" width="180px">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.activitySignStartTime) }} -- {{ formatDate(scope.row.activitySignEndTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="活动时间" width="180px">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.activityConStartTime) }} -- {{ formatDate(scope.row.activityConEndTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报名情况" v-slot="{ row }">
          <template>
  <span
      :class="{
      'status-pending': row.IfCheck === 2,
      'status-success': row.IfCheck === 3,
      'status-failure': row.IfCheck === 4,
      'status-default': ![2, 3, 4].includes(row.IfCheck)
    }"
  >
    <span v-if="row.IfCheck === 2">已报名(审核中)</span>
    <span v-else-if="row.IfCheck === 3">报名成功</span>
    <span v-else-if="row.IfCheck === 4">报名失败</span>
    <span v-else>未报名</span>
  </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-slot="{ row }">
          <template>
            <el-button type="text" @click="showDetail(row)">查看详情</el-button>
            <!-- 可以添加其他操作按钮，比如报名 -->
          </template>
        </el-table-column>
        <el-table-column label="报名" v-slot="{ row }">
          <template>
            <el-button type="text" v-if="row.IfCheck===1" @click="Join(row)">报名</el-button>
            <el-button type="text" v-else-if="row.IfCheck===4" @click="Join(row)">重新报名</el-button>
            <el-button type="text" v-else @click="Exit(row)">退出</el-button>
            <!-- 可以添加其他操作按钮，比如报名 -->
          </template>
        </el-table-column>
        <el-table-column label="收藏" v-slot="{row}">
          <el-button @click="collect(row)" type="text">收藏</el-button>
        </el-table-column>
      </el-table>
      <el-dialog
          :visible.sync="dialogVisibleActivity"
          title="活动详情"
          :show-close="false"
      >
        <span>活动详情：</span>
        <p v-html="detail"></p>
        <img v-if="imageUrl" :src="imageUrl" alt="活动图片" style="max-width: 100%; height: auto;" />
        <el-button @click="downloadFile" v-if="imageUrl">下载图片</el-button>
        <el-button type="primary" @click="closeDialog">关闭</el-button>
      </el-dialog>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="个人信息" @close="resetForm">
      <el-form ref="personalForm" :model="personalInfo" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="this.userAccount" :disabled="true" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="选择学校">
          <el-select v-model="selectedSchool" placeholder="请选择学校">
            <el-option
                v-for="school in joinMiddleSchool"
                :key="school.id"
                :label="school.sname"
                :value="school.sname"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择地区">
          <el-cascader
              size="large"
              :options="pcaTextArr"
              v-model="selectedOptions"
              @change="insertStudentLocation(selectedOptions)"
          >
          </el-cascader>

        </el-form-item>
        <!-- 其他个人信息表单字段 -->
        <!-- ... -->
        <el-form-item>
          <el-button type="primary" @click="submitForm(selectedActivity)">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 可以添加其他组件，比如筛选条件、轮播图等 -->
  </div>
  </div>
</template>

<script>

import {getJoinActivity, queryIfJoin, Join, ExitActivity, getDetail, queryCheckStatus} from '../../../../api/activity'
import {mapGetters} from 'vuex'
import {joinMiddleSchool} from '../../../../api/middle'
import {deleteStudentSchool, insertStudentSchool} from '../../../../api/user'
import { pcaTextArr } from 'element-china-area-data'
import {deleteStudentLocation, downloadFile, insertStudentLocation} from '../../../../api/api'
import {getActivityUrl} from '../../../../api/activityUrl'
import {insertCollection} from '../../../../api/collect'
export default {
  name: 's-activity',
  inject: ['reload'],
  computed: {
    ...mapGetters({
      userRole: 'user/getUserRole',
      userAccount: 'user/getUserAccount',
      userId: 'user/getUserId'
    })
  },
  data () {
    return {
      pcaTextArr,
      detail: '',
      selectedOptions: [],
      activities: [],
      imageUrl: '',
      // 现有的数据属性
      dialogVisible: false, // 控制对话框的显示
      personalInfo: { // 存储个人信息的对象
        name: ''
        // 根据需要添加其他个人信息字段
      },
      dialogVisibleActivity: false,
      selectedSchool: '', // 存储用户选择的学校
      selectedActivity: null,
      joinMiddleSchool: [],
      ruleForm: '',
      studentLocation: {},
      activityTYPE: '',
      activityImage: []
    }
  },

  created () {
    this.showActivity()
    const IF = this.$route.params.id
    if (IF) {
      this.activityTYPE = 1
    } else {
      this.activityTYPE = 2
    }
    // 调用后端接口获取活动数据，并将数据赋值给 activities
    // 例如，可以在此调用 this.getJoinActivity() 来获取已参加的活动数据
    // 通过接口获取数据并将数据赋值给 this.activities
  },
  methods: {
    turnActivity (aid) {
      this.$router.push({name: 'activityDetail', params: {actId: aid}})
    },
    getActivityUrl () {
      for (const activity of this.activities) {
        getActivityUrl(activity.id).then(urlResult => {
          // 这里可以处理获取到的 URL 数据，比如将 URL 存储到活动对象中
          this.activityImage.push(urlResult[0].url) // 假设 urlResult 包含一个 URL 数组
        }).catch(error => {
          console.error('获取活动 URL 出错:', error)
        })
      }
      console.log(this.activityImage)
    },
    collect (activity) {
      insertCollection(this.userId, activity.id)
        .then(result => {
          this.$message.success('收藏成功')
        })
        .catch(error => {
          this.$message.warning('重复收藏')
          console.error('收藏时出错:', error)
        })
    },
    insertStudentLocation (selectedOptions) {
      this.studentLocation.uid = this.userId
      if (selectedOptions.length === 3) {
        this.studentLocation.province = selectedOptions[0]
        this.studentLocation.city = selectedOptions[1]
        this.studentLocation.district = selectedOptions[2]
      } else if (selectedOptions.length === 2) {
        this.studentLocation.province = selectedOptions[0]
        this.studentLocation.city = selectedOptions[1]
      } else if (selectedOptions.length === 1) {
        this.studentLocation.province = selectedOptions[0]
      }
    },
    formatDate (date) {
      const newDate = new Date(date)
      const year = newDate.getFullYear()
      const month = String(newDate.getMonth() + 1).padStart(2, '0')
      const day = String(newDate.getDate()).padStart(2, '0')
      return `${year}/${month}/${day}`
    },
    async showActivity () {
      const res = await getJoinActivity(this.userId)
      if (res && res.length > 0) {
        this.activities = res.filter(activity => {
          if (this.activityTYPE === 1) {
            return activity.type === 1
          } else if (this.activityTYPE === 2) {
            return activity.type === 2 || activity.type === 3
          }
          return false
        })

        await Promise.all(
          this.activities.map(async activity => {
            const check = await queryCheckStatus(this.userId, activity.id)
            this.$set(activity, 'IfCheck', check)
            const res = await queryIfJoin(this.userId, activity.id)
            this.$set(activity, 'IfJoin', res)
          })
        )
      }
      await this.getActivityUrl()
    },
    showDetail (activity) {
      Promise.all([getDetail(activity.id), getActivityUrl(activity.id)])
        .then(([detailResult, urlResult]) => {
          this.activityId = activity.id
          this.detail = detailResult.activityDescription
          this.imageUrl = urlResult[0].url // 获取第一个对象的 URL 属性
          this.dialogVisibleActivity = true
        })
        .catch(error => {
          // 处理错误
          console.error(error)
          this.$message.error('获取活动详情或链接时出错')
        })
    },
    closeDialog () {
      this.dialogVisibleActivity = false
    },
    downloadFile () {
      getActivityUrl(this.activityId).then(urlResult => {
        console.log(urlResult)
        let obj = {
          path: urlResult[0].url
        }
        downloadFile(obj)
          .then(response => {
            // 通过创建 Blob 对象来处理下载的文件
            const blob = new Blob([response], { type: 'image/jpeg' })

            // 创建一个 URL，用于文件下载
            const downloadUrl = window.URL.createObjectURL(blob)

            // 创建一个 <a> 标签来触发下载
            const link = document.createElement('a')
            link.href = downloadUrl
            link.download = decodeURIComponent(urlResult[0].fileName)
            link.style.display = 'none'

            document.body.appendChild(link)
            link.click()

            // 清理资源
            window.URL.revokeObjectURL(downloadUrl)
            document.body.removeChild(link)
          })
          .catch(error => {
            console.error(error)
            // 处理错误
          })
      })
    },
    Join (activity) {
      if (activity.activityMaxNum === activity.activityNum) {
        this.$message.error('人数以满')
      } else {
        joinMiddleSchool(activity.id).then(result => {
          this.joinMiddleSchool = result
        })
        this.selectedActivity = activity
        this.dialogVisible = true
      }
    },
    submitForm (activity) {
      this.studentLocation.aid = activity.id
      this.dialogVisible = false
      Join(this.userId, activity.id).then(res => {
        insertStudentSchool(this.userId, activity.id, this.selectedSchool)
        insertStudentLocation(this.studentLocation)
        if (res === ('成功')) {
          this.$message({
            message: '提交成功',
            type: 'success'
          })
        }
      })
      this.reload()
    },
    resetForm () {
      // 重置表单
      this.$refs.personalForm.resetFields()
      this.selectedSchool = ''
    },
    Exit (activity) {
      ExitActivity(this.userId, activity.id).then(res => {
        deleteStudentSchool(this.userId, activity.id)
        deleteStudentLocation(this.userId, activity.id)
        if (res === ('成功')) {
          this.$message({
            message: '恭喜你，这是一条成功消息',
            type: 'success'
          })
        }
      })
      this.reload()
    }

    // 可以添加其他方法，比如报名操作等
  }
}
</script>

<style scoped>
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}
.el-table th.el-table__cell{
  background-color: transparent;
}
.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

.stats-card {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px 20px; /* 减小卡片的上下长度 */
}

.stats-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 200px; /* 调整字段之间的间距 */
  position: relative;
}

.stats-item {
  text-align: center;
}

/* 新增样式用于虚线 */
.stats-dotted-line {
  position: absolute;
  height: 100%;
  width: 1px; /* 虚线的宽度 */
  background-image: linear-gradient(to bottom, black 20%, rgba(255, 255, 255, 0) 0%);
  background-position: 50%;
  background-size: 1px 10px; /* 控制虚线的高度和间距 */
  background-repeat: repeat-y;
  top: 0;
  bottom: 0;
  left: calc(20% - 1px); /* 将虚线置于两字段之间的中间位置 */
}

.stats-dotted-line2 {
  position: absolute;
  height: 100%;
  width: 1px; /* 虚线的宽度 */
  background-image: linear-gradient(to bottom, black 20%, rgba(255, 255, 255, 0) 0%);
  background-position: 50%;
  background-size: 1px 10px; /* 控制虚线的高度和间距 */
  background-repeat: repeat-y;
  top: 0;
  bottom: 0;
  left: calc(50% - 1px); /* 将虚线置于两字段之间的中间位置 */
}
.stats-dotted-line3 {
  position: absolute;
  height: 100%;
  width: 1px; /* 虚线的宽度 */
  background-image: linear-gradient(to bottom, black 20%, rgba(255, 255, 255, 0) 0%);
  background-position: 50%;
  background-size: 1px 10px; /* 控制虚线的高度和间距 */
  background-repeat: repeat-y;
  top: 0;
  bottom: 0;
  left: calc(80% - 1px); /* 将虚线置于两字段之间的中间位置 */
}
.stats-label {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px; /* 调整字段与数字之间的间距 */
}

.stats-value {
  font-size: 32px;
  font-weight: bold;
}
/deep/ .el-table__header{
  background-color: transparent;
}
.el-table__header{
  background-color: transparent;
}
/*最外层透明*/
/deep/ .el-table, /deep/ .el-table__expanded-cell{
  background-color: transparent;
}
/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td {
  background-color: transparent;
}

.status-pending {
  color: orange; /* 将 '已报名(审核中)' 的文本设为橙色 */
}

.status-success {
  color: green; /* 将 '报名成功' 的文本设为绿色 */
}

.status-failure {
  color: red; /* 将 '报名失败' 的文本设为红色 */
}

.status-default {
  /* 默认状态的样式，可以添加其他样式或者保持默认状态 */
}
/* 可以在这里添加样式 */
/* 示例中的样式是简单的示范，请根据实际需要进行样式调整 */
.activity-list {
  padding: 20px;
}
</style>
